package com.glela.api.upload.qiniu.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.apache.commons.httpclient.HttpException;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glela.api.upload.qiniu.IQiniuService;
import com.glela.api.upload.qiniu.http.HttpProtocolHandler;
import com.glela.api.upload.qiniu.http.HttpRequest;
import com.glela.api.upload.qiniu.http.HttpResponse;
import com.glela.api.upload.qiniu.http.HttpResultType;
import com.glela.api.upload.util.FopParse;
import com.glela.api.upload.util.FopParse.Item;
import com.glela.api.upload.util.ImageProperties;
import com.glela.api.upload.util.VideoProperties;
import com.glela.api.upload.util.UpLoadConfig;
import com.glela.api.upload.util.qryTask;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.processing.OperationManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.StringUtils;

@Service("mediaService")
public class QiniuService implements IQiniuService
{

	private static final Logger logger = Logger.getLogger(UploadObject.class);

	@Override
	public Map<String, Object> getVideoImgByQnId(String id) throws HttpException, Exception
	{

		Map<String, Object> resMap = new HashMap<String, Object>();
		resMap.put("success", false);
		VideoProperties videoProperties = new VideoProperties();
		List<ImageProperties> imageList = new ArrayList<ImageProperties>();
		logger.info("put media image to Qiniu result >> " + id);
		//通过HTTPGET请求获取该ID下的视频和视频截图信息
		HttpRequest request = new HttpRequest(HttpResultType.STRING);
		//设置格式码
		request.setCharset("utf-8");
		//设置超时时间
		request.setConnectionTimeout(60000);
		//get类型提交
		request.setMethod("GET");
		//设置请求的参数ID
		request.setQueryString("id=" + id);
		//查询七牛的URL
		request.setUrl(UpLoadConfig.httpTask);

		//执行请求
		//		ExecutorService executor = Executors.newCachedThreadPool();
		//		qryTask task = new qryTask(request);
		//		Future<HttpResponse> tt = executor.submit(task);
		//		HttpResponse response = tt.get();
		//		executor.shutdown();
		HttpResponse response = HttpProtocolHandler.getInstance().execute(request);

		logger.info("get Result  message:==>" + response.getStringResult());
		//请求是否成功
		if (response.isSucced()) {
			String jsonResult = response.getStringResult();
			JSONObject result = JSON.parseObject(jsonResult);

			//当返回状态为处理成功或者为等待处理时
			if ("0".equals(result.getString("code")) || "1".equals(result.getString("code"))) {
				List<Item> list = new FopParse(UpLoadConfig.httpBase).parse(jsonResult);
				for (Item i : list) {
					//判断是否为视频
					if (i.isMp3()) {
						videoProperties.setVideoPath(i.getKey());
						videoProperties.setKey(id);
						continue;
					}
					else {
						//否则为图片，这里图片先设置一张
						ImageProperties imageProperties = new ImageProperties();
						imageProperties.setImagePath(i.getKey()); //视频截图路径
						//						imageProperties.setHeight(height);
						//						imageProperties.setWidth(width);
						imageList.add(imageProperties);
					}
				}
				//设置图片和视频信息的BEAN  并返回

				resMap.put("videoProperties", videoProperties);
				resMap.put("imageProperties", imageList);
				resMap.put("success", true);

			}
			else {
				resMap.put("success", false);
			}

		}

		return resMap;

	}

	/**
	 * 上传截图
	 * 
	 * @param name
	 *            七牛保存的文件名称
	 * @param bitRate
	 *            码率
	 * @param width
	 *            宽
	 * @param height
	 *            高
	 * @return
	 * @throws Exception
	 * @throws HttpException
	 */
	public String pfopVideo(Auth auth, String name, String bitRate, String width, String height, String videoType)
	{
		OperationManager operater = new OperationManager(auth);

		Map<String, Object> resMap = new HashMap<String, Object>();
		StringBuilder fops = new StringBuilder(256);
		fops.append("avthumb/" + videoType + "/aspect/16:9"); //设置播放器中显示的宽高比
		fops.append("/ab/" + bitRate + ";"); //设置码率
		for (int i = 2; i < 22; i += 2) {
			fops.append("vframe/jpg/offset/"); //设置截图的宽和高
			fops.append(i);
			fops.append("/w/" + width + "/h/" + height + ";");
		}
		//convertMedia
		StringMap params = new StringMap().putNotEmpty("notifyURL", UpLoadConfig.callbackUrl)
				.putNotEmpty("bucket", UpLoadConfig.bucket).putNotEmpty("key", name).putNotEmpty("fops", fops.toString())
				.putNotEmpty("force", "1").put("pipeline", "liujie");

		try {

			//获取视频信息在七牛中的ID
			String id = operater.pfop(UpLoadConfig.bucket, name, fops.toString(), params);
			//通过HTTP  get请求QN的信息
			if (!StringUtils.isNullOrEmpty(id)) {

				//			resMap = getQNInfoHttpMessage(width, height, id);
				resMap.put("QNId", id);
				return id;
			}
			else {
				return null;
			}

		}
		catch (QiniuException e) {
			Response r = e.response;
			logger.error(r.toString());
			logger.error(e.getMessage(),e);
			try {
				logger.error(r.bodyString());
				return null;
			}
			catch (QiniuException e1) {
				logger.error(e1.getMessage(),e1);
			}
			return null;
		}

	}

	@Override
	public Map<String, Object> uploadImage(byte[] mediaContent, String width, String height)
	{
		Auth auth = Auth.create(UpLoadConfig.accessKey, UpLoadConfig.secretKey);
		//实例化七牛
		UploadManager uploadManager = new UploadManager();
		//通过bucket获取token
		String token = auth.uploadToken(UpLoadConfig.bucket);
		SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMDDHHmmss");
		String key = sdf.format(new Date()) + GeneratorRandom.genratorRandomString(5);
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			//开始上传视频
			Response response = uploadManager.put(mediaContent, key, token);
			logger.info("put media to Qiniu result >> " + response.toString());
			// 处理截图
			if (response.isOK()) {
				ImageProperties imagePropertie = response.jsonToObject(ImageProperties.class);

				try {
					resMap = pfopImage(auth, key, width, height, imagePropertie);
					if (resMap != null) {

						return resMap;
					}
					else {

						return null;
					}
				}
				catch (HttpException e) {
					logger.error(e.getMessage(),e);
				}
				catch (Exception e) {
					logger.error(e.getMessage(),e);
				}

			}

			return null;
		}
		catch (QiniuException e) {
			logger.error(e.getMessage(),e);
		}

		return null;
	}

	@Override
	public Map<String, Object> uploadVideo(byte[] mediaContent)
	{
		return uploadVideo(mediaContent, "384k", "760", "380", "mp4");

	}

	/* (non-Javadoc)
	 * @see com.glela.common.api.upload.IQiniuService#uploadVideo(byte[], java.lang.String, java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	public Map<String, Object> uploadVideo(byte[] mediaContent, String bitRate, String width, String height, String videoType)
	{
		Auth auth = Auth.create(UpLoadConfig.accessKey, UpLoadConfig.secretKey);

		Map<String, Object> resMap = new HashMap<String, Object>();
		resMap.put("success", "false");

		//实例化七牛
		UploadManager uploadManager = new UploadManager();
		//通过bucket获取token
		String token = auth.uploadToken(UpLoadConfig.bucket);
		//		logger.debug("生成TOKEN:" + token);
		SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMDDHHmmss");
		String key = sdf.format(new Date()) + GeneratorRandom.genratorRandomString(5);

		try {
			//开始上传视频
			Response response = uploadManager.put(mediaContent, key, token);
			logger.info("put media to Qiniu result >> " + response.toString());
			// 处理截图
			if (response.isOK()) {
				VideoProperties videoProperties = response.jsonToObject(VideoProperties.class);

				String id = pfopVideo(auth, key, bitRate, width, height, videoType);
				resMap.put("qnId", id);
				resMap.put("saveKey", key);
				resMap.put("videoProperties", videoProperties);

				resMap.put("success", "true");
				return resMap;

			}
			else {
				return resMap;
			}

		}
		catch (QiniuException e) {
			logger.error(e.getMessage(),e);
			return resMap;
		}
	}

	private Map<String, Object> pfopImage(Auth auth, String name, String width, String height, ImageProperties imagePropertie)
			throws HttpException, Exception
	{
		OperationManager operater = new OperationManager(auth);
		JSONObject result = null;
		ImageProperties imageProperties = new ImageProperties();
		Map<String, Object> resMap = new HashMap<String, Object>();
		StringBuilder fops = new StringBuilder(256);

		fops.append("imageView2/1/w/" + width + "/h/" + height + ";"); //设置播放器中显示的宽高比
		//convertMedia
		StringMap params = new StringMap().putNotEmpty("notifyURL", UpLoadConfig.callbackUrl)
				.putNotEmpty("bucket", UpLoadConfig.bucket).putNotEmpty("key", name).putNotEmpty("fops", fops.toString())
				.putNotEmpty("force", "1").put("pipeline", "liujie");

		try {

			//获取视频信息在七牛中的ID
			String id = operater.pfop(UpLoadConfig.bucket, name, fops.toString(), params);
			//通过HTTPGET请求获取该ID下的视频和视频截图信息
			HttpRequest request = new HttpRequest(HttpResultType.STRING);
			//设置格式码
			request.setCharset("utf-8");
			//设置超时时间
			request.setConnectionTimeout(60000);
			//get类型提交
			request.setMethod("GET");
			//设置请求的参数ID
			request.setQueryString("id=" + id);
			//查询七牛的URL
			request.setUrl(UpLoadConfig.httpTask);
			//执行请求
			ExecutorService executor = Executors.newCachedThreadPool();
			qryTask task = new qryTask(request);
			Future<HttpResponse> tt = executor.submit(task);
			HttpResponse response = tt.get();
			executor.shutdown();

			//请求是否成功
			if (response.isSucced()) {
				String jsonResult = response.getStringResult();
				result = JSON.parseObject(jsonResult);
				if ("0".equals(result.getString("code")) || "3".equals(result.getString("code"))) {
					List<Item> list = new FopParse(UpLoadConfig.httpBase).parse(jsonResult);
					for (Item i : list) {
						//判断是否为视频
						if (i.isMp3()) {

							continue;
						}
						else {
							//否则为图片，这里图片先设置一张
							imageProperties.setImagePath(i.getKey()); //视频截图路径
							imageProperties.setHeight(height);
							imageProperties.setWidth(width);
							break;
						}
					}
					result.put("success", true);
					result.put("items", list);
				}
				else {
					result.put("success", false);
				}
			}

			logger.info("put media image to Qiniu result >> " + id);

			//设置图片信息的BEAN  并返回

			resMap.put("imageProperties", imageProperties);
			return resMap;
		}
		catch (QiniuException e) {
			Response r = e.response;
			logger.error(r.toString());
			logger.error(e.getMessage(),e);
			try {
				logger.error(r.bodyString());
				return null;
			}
			catch (QiniuException e1) {
				logger.error(e1.getMessage(),e1);
			}
			return null;
		}

	}

}
